"use client"

import { useAuthStore } from '@/store/useAuthStore'
import { useState, useEffect, useCallback, Suspense } from "react"
import { useSearchParams } from "next/navigation"
// 中间件 接收参数
const SubComponent = () => {
  const searchParams = useSearchParams()
  const {setToken} = useAuthStore()

  const sendMessage = (message: any) => {
    window.top && window.top.postMessage(message, '*')
  }

  useEffect(() => {
    let store: any = {}
    if (!searchParams) return
    searchParams.forEach((value, key) => {
      store[key] = value
    })

    // 有storageName才处理
    if (store.storageName) {
      const name = store.storageName
      delete store.storageName

      // 处理特殊参数 比如Token 单独处理并存到指定的localStorage
      if (store.access_token) {
        setToken(store.access_token)
        delete store.access_token
      }
      localStorage.setItem(name, JSON.stringify(store))
      sendMessage(name)
    }
  }, [])
  return <Suspense>middleStore</Suspense>
}

const MiddleStore = () => {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <SubComponent />
    </Suspense>
  );
}

export default MiddleStore
